﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using System.IO;
using Microsoft.AspNetCore.Http;
using System.Net.Http.Headers;


namespace DH.Web.MVC.Controllers.Api
{
    [Route("api/uploadFile")]
    public class UploadFileApiController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public IActionResult Post()
        {
            try
            {
                var upfilePath = "";
                var files = Request.Form.Files;
                if (files.Any())
                {
                    var file = files[0];

                    var filename = "";
                    //var filename = ContentDispositionHeaderValue
                    //                .Parse(file.ContentDisposition)
                    //                .FileName
                    //                .Trim('"');

                    string fileNameTime = DateTime.Now.ToString("yyyyMMddhhmmss");

                    var bootPath = "File/img/userImg";
                    var fullPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", bootPath);
                    if (false == Directory.Exists(fullPath))
                    {
                        Directory.CreateDirectory(fullPath);
                    }

                    filename = fullPath + $@"\{fileNameTime}.jpg";
                    upfilePath = bootPath + $@"/{fileNameTime}.jpg";
                    using (FileStream fs = System.IO.File.Create(filename))
                    {
                        file.CopyTo(fs);
                        fs.Flush();
                    }

                    
                }
                return new JsonResult(new { Status = 200, filePath = upfilePath });
            }
            catch (Exception ex) {
                
                return new JsonResult(new { Status = 500, filePath = "" });
            }
            


        }
      
    }
}